package second.thread.threadlocaltest;

import lombok.Data;

import java.util.concurrent.CountDownLatch;

/**
 * @Author: heweiwei
 * @Date: 3/16/25 PM1:56
 * @Description:
 */
@Data
public class ThreadLocalTest {

    private int count1 = 0;
    private int count2 = 0;

    private ThreadLocal<Integer> personalThread = ThreadLocal.withInitial(() -> 0);

    public void salePersonal() {
        personalThread.set(personalThread.get() + 1);
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalTest test = new ThreadLocalTest();
        CountDownLatch countDownLatch = new CountDownLatch(20);

        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                try {
                    test.salePersonal();
                    System.out.println(Thread.currentThread().getName() + "卖了" + test.personalThread.get() + "车");
                    Integer saleCount = test.personalThread.get();
                    test.count1 = test.count1 + saleCount;
                    synchronized (test) {
                        test.count2 = test.count2 + saleCount;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                    test.personalThread.remove();
                }
            }).start();
        }
        countDownLatch.await();
        System.out.println("一共卖了" + test.count1 + "车");
        System.out.println("一共卖了" + test.count2 + "车");
        //此处是0的原因是因为每个线程都有自己的ThreadLocal,main线程也有,初始为0
        System.out.println("一共卖了" + test.personalThread.get() + "车");

    }
}
